# 构建阶段
FROM python:3.11-slim as builder

WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# 安装系统依赖
RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc \
    python3-dev \
    && rm -rf /var/lib/apt/lists/*

# 安装虚拟环境
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# 安装Python依赖
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 生产阶段
FROM python:3.11-slim

# 设置容器参数
ENV PORT=8080 \
    TIMEOUT=10 \
    MAX_CODE_LENGTH=4096 \
    WORKERS=2 \
    LOG_LEVEL=info

# 创建非特权用户
RUN addgroup --gid 1001 codegroup && \
    adduser --disabled-password --gecos '' --uid 1001 --gid 1001 codeuser

WORKDIR /app

# 从构建阶段复制虚拟环境
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# 复制应用代码
COPY . .

# 设置权限
RUN chown -R codeuser:codegroup /app && \
    chmod 755 /app/entrypoint.sh

# 切换用户
USER codeuser

# 设置资源限制
RUN ulimit -n 1024

# 入口脚本
ENTRYPOINT ["/app/entrypoint.sh"]
